package cn.xhjava.crm.workbench.controller;

import cn.xhjava.crm.commons.ReturnObject;
import cn.xhjava.crm.commons.SysContants;
import cn.xhjava.crm.commons.util.DateUtils;
import cn.xhjava.crm.commons.util.ExceptionUtil;
import cn.xhjava.crm.settings.domain.DicValue;
import cn.xhjava.crm.settings.domain.User;
import cn.xhjava.crm.settings.service.DicValueService;
import cn.xhjava.crm.settings.service.UserService;
import cn.xhjava.crm.workbench.domain.*;
import cn.xhjava.crm.workbench.service.*;
import org.apache.ibatis.transaction.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Author:   XiaHu
 * Date:     2023/6/27
 * 客户
 */
@Controller
public class TransactionController {
    private static final Logger log = LoggerFactory.getLogger(TransactionController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private DicValueService dicValueService;

    @Autowired
    private TranService tranService;

    @Autowired
    private TranHistoryService tranHistoryService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private TransactionRemarkRemarkService transactionRemarkService;


    @RequestMapping("/workbench/transaction/index")
    public String index(HttpServletRequest request) {
        log.info("跳转到 transaction index");
        List<User> userList = null;
        List<DicValue> sourceList = null;
        List<DicValue> stageList = null;
        List<DicValue> transactionTypeList = null;
        try {
            userList = userService.queryAllUsers();
            sourceList = dicValueService.queryDicValueByTypeCode("source");
            stageList = dicValueService.queryDicValueByTypeCode("stage");
            transactionTypeList = dicValueService.queryDicValueByTypeCode("transactionType");
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        request.setAttribute("userList", userList);
        request.setAttribute("stageList", stageList);
        request.setAttribute("sourceList", sourceList);
        request.setAttribute("transactionTypeList", transactionTypeList);
        return "workbench/transaction/index";
    }

    @RequestMapping("/workbench/transaction/toUpdate")
    public String toUpdate(String id, HttpServletRequest request) {
        List<User> userList = null;
        List<DicValue> sourceList = null;
        List<DicValue> stageList = null;
        List<DicValue> transactionTypeList = null;
        Tran transaction = null;
        try {
            userList = userService.queryAllUsers();
            sourceList = dicValueService.queryDicValueByTypeCode("source");
            stageList = dicValueService.queryDicValueByTypeCode("stage");
            transactionTypeList = dicValueService.queryDicValueByTypeCode("transactionType");
            transaction = tranService.selectDetailById(id);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        request.setAttribute("userList", userList);
        request.setAttribute("stageList", stageList);
        request.setAttribute("sourceList", sourceList);
        request.setAttribute("transactionTypeList", transactionTypeList);
        request.setAttribute("transaction", transaction);
        return "workbench/transaction/edit";
    }

    @RequestMapping("/workbench/transaction/queryTransactionByConditionForPage")
    public @ResponseBody
    Object queryclueByConditionForPage(String owner,
                                       String name,
                                       String customerName,
                                       String stage,
                                       String type,
                                       String source,
                                       String contactsName,
                                       int pageNo, int pageSize, HttpSession session) {
        User user = (User) session.getAttribute(SysContants.SESSION_USER);
        //封装参数
        Map<String, Object> map = new HashMap<>();
        map.put("owner", owner);
        map.put("name", name);
        map.put("customerName", customerName);
        map.put("contactsName", contactsName);
        map.put("source", source);
        map.put("stage", stage);
        map.put("type", type);
        map.put("beginNo", (pageNo - 1) * pageSize);
        map.put("pageSize", pageSize);
        //调用service层方法，查询数据
        List<Tran> transactionList = null;
        int totalRows = 0;
        try {
            transactionList = tranService.selectForPage(map);
            totalRows = tranService.selectCountForPage(map);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }

        Map<String, Object> retMap = new HashMap<>();
        retMap.put("transactionList", transactionList);
        retMap.put("totalRows", totalRows);
        return retMap;
    }

    @RequestMapping("/workbench/transaction/getPossibilityByStage")
    public @ResponseBody
    Object getPossibilityByStage(String stageValue) {
        //解析properties配置文件，根据阶段获取可能性
        ResourceBundle bundle = ResourceBundle.getBundle("possibility");
        String possibility = bundle.getString(stageValue);
        //返回响应信息
        return possibility;
    }

    @RequestMapping("/workbench/transaction/queryCustomerNamesLikeName")
    public @ResponseBody
    Object queryCustomerNameByName(String customerName) {
        List<String> customerNameList = null;
        try {
            customerNameList = customerService.queryCustomerNamesLikeName(customerName);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        //根据查询结果，返回响应信息
        return customerNameList;
    }

    @RequestMapping("/workbench/transaction/add")
    public @ResponseBody
    Object add(@RequestParam Map<String, Object> map, HttpSession session) {
        //封装参数
        map.put(SysContants.SESSION_USER, session.getAttribute(SysContants.SESSION_USER));

        ReturnObject returnObject = new ReturnObject();
        try {
            tranService.add(map);
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_SUCCESS);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙，请稍后重试....");
        }

        return returnObject;
    }

    // 删除
    @RequestMapping("/workbench/transtaction/delete")
    public @ResponseBody
    Object delete(String[] id) {
        ReturnObject returnObject = new ReturnObject();
        try {
            //调用service层方法，删除市场活动
            int ret = tranService.delete(id);
            if (ret > 0) {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_SUCCESS);
            } else {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统忙，请稍后重试....");
            }
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙，请稍后重试....");
        }
        return returnObject;
    }

    @RequestMapping("/workbench/transtaction/deleteById")
    public @ResponseBody
    Object deleteById(String transactionId) {
        ReturnObject returnObject = new ReturnObject();
        try {
            int ret = tranService.deleteById(transactionId);
            if (ret > 0) {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_SUCCESS);
            } else {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统忙，请稍后重试....");
            }
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙，请稍后重试....");
        }
        return returnObject;
    }


    // 查询
    @RequestMapping("/workbench/transtaction/queryTransactionById")
    public @ResponseBody
    Object selectById(String id) {
        Tran tran = null;
        try {
            tran = tranService.selectDetailById(id);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        return tran;
    }


    @RequestMapping("/workbench/transaction/update")
    public @ResponseBody
    Object update(Tran transaction, HttpSession session) {
        User user = (User) session.getAttribute(SysContants.SESSION_USER);
        transaction.setEditTime(DateUtils.formateDateTime(new Date()));
        transaction.setEditBy(user.getId());

        ReturnObject returnObject = new ReturnObject();
        try {
            int ret = tranService.update(transaction);

            if (ret > 0) {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_SUCCESS);
            } else {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统忙，请稍后重试....");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙，请稍后重试....");
        }
        return returnObject;
    }


    @RequestMapping("/workbench/transaction/detailById")
    public String detail(String id, HttpServletRequest request) {
        Tran tran = null;
        List<DicValue> stageList = null;
        List<TranHistory> tranHistoryList = null;
        List<TranRemark> remarkList = null;
        try {
            tran = tranService.selectDetailById(id);
            stageList = dicValueService.queryDicValueByTypeCode("stage");
            tranHistoryList = tranHistoryService.selectDetailByTranId(id);
            remarkList = transactionRemarkService.selectDetailByTranId(id);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }

        //根据tran所处阶段名称查询可能性
        ResourceBundle bundle = ResourceBundle.getBundle("possibility");
        String possibility = bundle.getString(tran.getStage());
        tran.setPossibility(possibility);

        request.setAttribute("stageList", stageList);
        request.setAttribute("tranHistoryList", tranHistoryList);
        request.setAttribute("remarkList", remarkList);
        request.setAttribute("tran", tran);
        return "workbench/transaction/detail";
    }
}
